package cn.simon.free.redis.mq.core.consumer;

import cn.simon.free.redis.mq.enums.ConsumerType;
import cn.simon.free.redis.mq.model.Message;
import cn.simon.free.redis.mq.model.normal.NormalMessage;
import cn.simon.free.redis.mq.model.normal.NormalMessageRo;

import java.util.Objects;
import java.util.Optional;

/**
 * 普通消息队列
 *
 * @author simon
 * @date 2021/7/1 16:38
 * @copyright:
 * @modifier
 * @motto a no talent, people who have to study hard
 */
public abstract class NormalRedisMessageConsumer<T> extends AbstractRedisMessageConsumer<T> {

    @Override
    public final Message getMessage(String queueName, ConsumerType consumerType) {
        NormalMessage message = (NormalMessage) redisMessageSupport.isClusterAndGetMessage(queueName, consumerType);
        if (Optional.ofNullable(message).isPresent()) {
            NormalMessageRo delayMessageRo = redisMessageNormalRoSupport.get(message.getTaskId());
            //对象message不存在,直接删除延迟队列中的数据
            if (Objects.isNull(delayMessageRo)) {
                redisMessageSupport.delete(queueName, message);
                return null;
            }
            message.setMessage(delayMessageRo.getMessage());
            return message;
        }
        return null;
    }

    @Override
    public final void deleteMessage(String queueName, Message message) {
        redisMessageSupport.delete(queueName, message);
        redisMessageNormalRoSupport.deleteByExpire(message.getTaskId());
    }

    /**
     * 普通消息队列,重新推送到队列,必须是集群{@link ConsumerType.CLUSTER}模式,子类{@link process()},
     * 返回false时,会自行触发. 不同于延迟消息队列,延迟队列有时间参与计算,未到时间时,需要自动触发{@code rePushMessage()}
     *
     * @param queueName
     * @param message
     * @param consumerType
     */
    @Override
    public final void rePushMessage(String queueName, Message message, ConsumerType consumerType) {
        if (redisMessageSupport.isCluster(consumerType)) {
            redisMessageSupport.push(queueName, message, 0L);
        }
    }
}
